package com.xinguan.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * @author lawrence
 * @create 2020-11-13
 */
public class FileUtils {

    private static Logger log = LoggerFactory.getLogger(FileUtils.class);

    public static void decompress(File file) throws IOException {
        ZipInputStream zin;//创建ZipInputStream对象
        try {
            ZipFile zipFile = new ZipFile(file);//创建压缩文件对象
            zin = new ZipInputStream(new FileInputStream(file));//实例化对象，指明要解压的文件
            ZipEntry entry;
            String path = file.getPath().substring(0, file.getPath().lastIndexOf(".")) + File.separator;
            while (((entry = zin.getNextEntry()) != null) && !entry.isDirectory()) {//如果entry不为空，并不在同一个目录下
                File tmp = new File(path + entry.getName());//解压出的文件路径
//                if (!tmp.exists()){//如果文件不存在
                tmp.getParentFile().mkdirs();//创建文件父类文件夹路径
                OutputStream os = new FileOutputStream(tmp);//将文件目录中的文件放入输出流
                //用输入流读取压缩文件中制定目录中的文件
                InputStream in = zipFile.getInputStream(entry);
                int count = 0;
                while ((count = in.read()) != -1) {//如有输入流可以读取到数值
                    os.write(count);//输出流写入
                }
                os.close();
                in.close();
//                }
                zin.closeEntry();
            }
            zin.close();

        } catch (IOException e) {
            log.error("解压文件异常", e);
            throw e;
        }
    }

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }
        System.out.println("info:"+url+" download success");
    }

    /**
     * 读取文件流转换为byte数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void main(String[] args) {
        String fileUrl = "http://update.cz88.net/soft/setup.zip";
        String fileName = "setup.zip";
        String savePath = "E:\\\\xinguan-v2\\\\xinaguan-admin-v2\\\\src\\\\main\\\\resources";

        try {
            downLoadFromUrl(fileUrl, fileName, savePath);
            decompress(new File(savePath + File.separator + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
